﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using dacli.modelos.clases;
using System.Windows.Forms;

namespace dacli.modelos.dao
{
    public abstract class EntidadDao
    {
        public string tabla {get;set;}
        protected Conexion conexion { get; set; }
        public EntidadDao(string tabla)
        {
            this.tabla = tabla;
            this.conexion = new Conexion();
        }
        public abstract long incluir();
        public abstract long modificar();
        public abstract long eliminar();
        public abstract bool consultar(string filtro);
        public bool existe(string filtro)
        { 
            string sql = "SELECT * FROM " + this.tabla + " WHERE "
+ filtro;
            SqlDataReader reader = conexion.consultar(sql);
            return reader.Read();

        }
        public void actualizar(string filtro)
        {
            if (!existe(filtro))
                incluir();
            else
                modificar();

        }
        public ComboBox llenarCombo(string campo, string filtro ="")
        {
            List<ElementoCombo> lista = new List<ElementoCombo>();
            ElementoCombo elemento = new ElementoCombo();
            lista.Add(elemento);
            String sql;
            if (String.IsNullOrEmpty(filtro))
            {
                sql = "SELECT * FROM " + tabla;
            }
            else
            {
                sql = "SELECT * FROM " + tabla + " WHERE   " + filtro;
            }
            SqlDataReader reader = conexion.consultar(sql);
            while (reader.Read())
            {
                elemento = new ElementoCombo(Convert.ToInt32(reader["id"].ToString()), reader[campo].ToString());
                lista.Add(elemento);
            }
            ComboBox combo = new ComboBox();
            combo.DataSource = lista;
            combo.DisplayMember = campo;
            combo.ValueMember = "id";
            return combo;
        }
        public List<String> listar(string campo, string filtro="", string orden="")
        {
            List<String> lista = new List<String>();                        
            String sql;
            String elemento;            
            if (String.IsNullOrEmpty(filtro))
            {
                sql = "SELECT * FROM " + tabla;
            }
            else
            {
                sql = "SELECT * FROM " + tabla + " WHERE   " + filtro;
            }
            if (!String.IsNullOrEmpty(orden))
            {
                sql += " ORDER BY " + orden;
            }
            SqlDataReader reader = conexion.consultar(sql);
            while (reader.Read())
            {
                elemento=  reader[campo].ToString();
                lista.Add(elemento);
            }
            return lista;
        }
    }
}
